<template>
  <div ref="map-container" style="height: 600px;position: relative;">
    <o-map ref="map" :vector="true" @get-ready="ready($event)" />
    <popup ref="popup">
      No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China
    </popup>
  </div>
</template>

<script>
import Feature from "ol/Feature.js";
import Point from 'ol/geom/Point.js';
import {Icon, Style} from 'ol/style.js';
import { fromLonLat, toLonLat } from 'ol/proj'

import oMap from '@/map/index'
import popup from "@/map/components/popup";

export default {
  name: 'App',
  components: {oMap, popup},
  data() {
    return {
      siteData: [
        {lon: 104.912777, lat: 34.730746, status: "offline"}
      ]
    }
  },
  methods: {
    ready(map) {
      this.map = map;
      this.$refs.popup.init(map);
      this.test();
    },
    test() {
      let {vectorLayer, vectorSource} = this.$refs.map;
      vectorLayer.setStyle(this.iconStyleFunction);

      this.siteData.forEach(item => {
        let pointFeature = new Feature({
          geometry: new Point(fromLonLat([item.lon, item.lat])),
          status: item.status,
          population: 4000,
          rainfall: 500
        });
        vectorSource.addFeature(pointFeature);
      });

      // 点击事件
      this.map.on('click', evt => {
        let feature = this.map.forEachFeatureAtPixel(evt.pixel, feature => feature);
        if (!feature) {
          return;
        }
        console.log("跳转点：" + feature.get("status"))
      });
      this.map.on('pointermove', e => {
        const pixel = this.map.getEventPixel(e.originalEvent);
        const hit = this.map.hasFeatureAtPixel(pixel);
        this.$refs['map-container'].style.cursor = hit ? 'pointer' : '';
      });
      /**
       * Add a click handler to the map to render the popup.
       */
      this.map.on('singleclick', evt => {
        const coordinate = evt.coordinate;
        this.$refs.popup.open(toLonLat(coordinate));
      });

    },
    iconStyleFunction(feature) {
      let style = "location_not_related";
      switch (feature.get("status")) {
        case "online":
          style = "location_online_related";
          break;
        case "offline":
          style = "location_offline_related";
          break;
        default:
          style = "location_not_related"
          break;
      }
      return new Style({
        image: new Icon({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: 'images/' + style + '.png',
        }),
      })
    }
  }
}
</script>

<style>

</style>
